The Java programming language provides an exception mechanism that makes programming easier. A piece of code would throw an exception if there is an unexpected situation. Most of the time, exceptions occur when there are errors and the programmers use the catch clause having prepared code to quit gracefully and emit a warning to aid debugging. Generally, the Java Virtual Machine (JVM) operates under the assumption that exceptions are rare and unexpected.
Programmers can use the base Exception class or derived classes provided in the Java application program interfaces (APIs), or define their own exception classes. FIG. 1A shows an example in which in the method main( ), the programmer, on line 110A, throws an exception while declaring the method. FIG. 1B shows an example in which the programmer allows the method TestInput( ) to throw an exception on lines 110B and 120B, and includes a catch command on line 130B to catch the exception.
Because the JVM does not allow access to an array with an index value below or above the range corresponding to the allocated size of the array, the JVM automatically detects the array-index overflows and throws an ArrayIndexOutOfBoundsException (AIOOBE) when such situation arises. Further, Java programmers do not need to check for a null pointer because the JVM would insert such a check and throw a NulIPointerException (NPE) if the pointer reference is null, e.g., 0. In the case of AIOOBE and NPE, the programmer is not required to add an explicit catch clause or declaration with the throw clause as in the example of FIG. 1A and FIG. B. However, the programmer would add such a clause to catch such exceptions if desired.
Certain programming methodologies can lead to a lot of exceptions being thrown. For example, when a programmer writes code for a particular situation thinking exception situation will be rare and handles it, but it turns out that exceptions occur quite often in some other execution condition which was not tested; when a programmer explicitly writes code using exceptions as a way to handle control flow and keep the code readable and clean, etc. However, excessive exceptions can lead to severe performance problems. For examples, some JVMs, which compile the bytecodes into native code after they reach a threshold of interpreting, leave the catch clauses uncompiled to keep the code-cache small. In these cases, when there is an exception, the control transfers from the compiled code to the exception handler in the run-time environment of the JVM which then passes the control to the interpreter to interpret the catch clause instructions. As a result, the entire transition process can be so costly that the JVM may decide to mark that method non-compilable and only interpret it. Consequently, the application performs much worse if the method is executed quite frequently in the interpreted mode, which, by its nature, performs poorly as compared to the compiled mode.